const app = getApp()

Page({
  data: {
    //当能够使用该API且未获得授权时，显示授权界面
    applyAuthority: false,

    hasUserInfo: false, // 页面已经拥有用户信息

    userIcon: '',
    userName: '',

    // 设备列表
    deviceList: [],

    // 下拉刷新
    triggered: false
  },

  onLoad: function () {
    // 将面页句柄保存到全局变量
    app.globals.pages['index'] = this

    if (app.globals.authorised && app.globals.userInfo) {
      this.setData({
        hasUserInfo: true
      })
      this.formatUseInfo()
      //console.log( app.globals.userInfo)
    }
    this.setData({
      applyAuthority: wx.canIUse('button.open-type.getUserInfo') && !app.globals.authorised,
    })
  },

  onReady: function () {
    this.fetchUserDevice();

    // 初始化websocket服务
    app.initWebsocket()
    console.log('index-ready')
  },

  onShow: function () {

  },

  /**
   * 渲染视图层
   * @param {object | undefined} deviceList 
   */
  render: function(deviceList){
    //console.log(deviceList)
    this.setData({
      deviceList: deviceList || this.data.deviceList
    })
  },

  /** 
   * 格式化渲染层用户数据 
   */ 
  formatUseInfo: function () {
    var userInfo = app.globals.userInfo
    this.setData({
      userIcon: userInfo.avatarUrl,
      userName: userInfo.nickName,
    })
  },

  /**
   * 用户数据准备好 回调
   */
  onUserInfoReady: function () {
    if (!this.data.hasUserInfo) {
      this.setData({
        hasUserInfo: true
      })
      this.formatUseInfo()
    }
  },

  // 获取用户信息授权回调
  getUserInfo: function (e) {
    //console.log(e)
    if (!e.detail.userInfo) {
      wx.showToast({ // 显示Toast
        title: '你拒绝了授权',
        icon: 'none',
        duration: 3000,
        mask: true

      })
    }
    else {
      var userInfo = e.detail.userInfo
      app.globals.userInfo = userInfo
      app.globals.authorised = true
      this.formatUseInfo()
      this.setData({
        hasUserInfo: true
      })
    }

  },

  // 工具按钮被点击
  toolTouched: function (event) {
    var toolName = event.currentTarget.dataset.name
    switch (toolName) {
      case 'add':
        wx.navigateTo({
          url: '/pages/device/device',
          events: {
            // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
            rxNewDevice: function (data) {
              console.log(data)
            },
          }
        })
        break
      default:
        break
    }
  },

  /**
   *  向服务器拉取用户设备数据
   * @param {boolean} showLoading 显示加载动画
   */
  fetchUserDevice: function (showLoading) {
    var page = this
    wx.request({
      method: 'POST',
      url: app.globals.host + 'LoginServlet', //登录
      data: {
        id: 17121899
      },
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      success(res) {
        var data = res.data
        if (data.suc) {
          var deviceList = [];
          var devices = data.device
          for (var i = 0; i < devices.length; i++) {
            //page.data.
            //devices[i].icon = "../../images/people.png"
            if(devices[i].art){
              devices[i].src = app.globals.host + 'images/device/preview/' + devices[i].art
            }
            deviceList.push(devices[i]);
          }
          page.render(deviceList)
          //console.log(deviceList)
        }
        else{
          var msg = ""
          if(typeof(data) == 'object'){
            msg = '服务器内部错误'
          }
          else{
            msg = '解码错误'
          }
          wx.showToast({ // 显示Toast
            title: msg,
            icon: 'none',
            duration: 2500,
            mask: false
          })
        }

        //console.log(res)
      },
      fail: function (res) {
        console.log(res)
        wx.showToast({ // 显示Toast
          title: '拉取信息失败',
          icon: 'none',
          duration: 3000,
          mask: false

        })
      },
      complete: function () {
        if (showLoading) {
          page.setData({
            triggered: false
          })
        }
      }
    })

    if (showLoading) {
    }
  },

  // 设备被点击
  deviceTouched: function (event) {
    var index = event.currentTarget.dataset.index
    if (index >= 0 && index < this.data.deviceList.length) {
      var device = this.data.deviceList[index]
      if (device.online) {
        // 跳转到详情面页
        wx.navigateTo({
          url: '/pages/session/seesion',

          success: function (res) {
            // 通过eventChannel向被打开页面传送数据
            res.eventChannel.emit('rxDevice', device)
          },

          fail: function (res) {
            wx.showToast({ // 显示Toast
              title: '请求失败',
              icon: 'none',
              duration: 2000,
              mask: true
            })
          }

        })
      }
      else {
        wx.showToast({ // 显示Toast
          title: '联系不上这个设备',
          icon: 'none',
          duration: 3000,
          mask: false
        })
      }

    }


  },

  // 下拉刷新回调
  refresh: function () {
    this.fetchUserDevice(true);
    this.setData({
      triggered: true
    })
  },

  /**
   * 接受到shocket消息 
   * 由app实例的WebsocketTask 分发事件
   * @param {object} devices 
   */
  onSocketMessage:function(devices){
    var deviceList = this.data.deviceList
    for(var i in devices){
      var deviceId = devices[i].deviceId
      for(var j in deviceList){
        if(deviceList[j].deviceId == deviceId){
          for(var k in devices[i]){
            deviceList[j][k] = devices[i][k]
          }
          break
        }
      }
    }
    this.render()

    // 更新当前设备会话
    if(app.globals.pages['session']){
      var session = app.globals.pages['session']
      var device = session.data.device
      console.log('更新当前会话')
      for(i in devices){
        if(devices[i].deviceId = device.deviceId){
          session.onSwitch(devices[i])
          //console.log(device)
          break
        }
      }
    }
  },

  /**
   * image 标签加载出错回调
   * @param {object} e 
   */
  onImageTagError:function(e){
    console.log(e)
  }
})
